import * as d3 from "d3";
import { defineComponent } from "@/shared/tools.mjs";

/**
 * @implements {ng.IController}
 */
export class LinePlotController {
  static $as = "LinePlotController";

  width = 640;

  height = 400;

  marginTop = 20;

  marginRight = 20;

  marginBottom = 20;

  marginLeft = 20;

  /**
   * @type {number[]}
   */
  data = d3.ticks(-2, 2, 200).map((d) => Math.sin(d));

  $onInit() {}

  /**
   * @param {number} i
   */
  x = (i) =>
    d3.scaleLinear(
      [0, this.data.length - 1],
      [this.marginLeft, this.width - this.marginRight],
    )(i);

  /**
   * @param {number} i
   */
  y = (i) =>
    d3.scaleLinear(
      // @ts-expect-error
      d3.extent(this.data),
      [this.height - this.marginBottom, this.marginTop],
    )(i);

  line() {
    return d3.line((d, i) => this.x(i), this.y)(this.data);
  }

  /**
   * @param {ng.IAngularEvent} $event
   */
  handleMousemove($event) {
    const [x, y] = d3.pointer($event);
    // console.log(x, y);
    this.data = [...this.data.slice(-200), Math.atan2(x, y)];
  }

  handleClick() {
    console.log("LinePlotController", this);
  }
}

export const D3Ng = defineComponent({
  controller: LinePlotController,
  controllerAs: LinePlotController.$as,
  template: html`
    <svg
      ng-attr-width="{{LinePlotController.width}}"
      ng-attr-height="{{LinePlotController.height}}"
      ng-mousemove="LinePlotController.handleMousemove($event)"
    >
      <path
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        ng-attr-d="{{LinePlotController.line()}}"
      />
      <g fill="white" stroke="currentColor" strokeWidth="1.5">
        <circle
          ng-attr-cx="{{LinePlotController.x($index)}}"
          ng-attr-cy="{{LinePlotController.y(d)}}"
          ng-repeat="d in LinePlotController.data track by $index"
          r="2.5"
        />
      </g>
    </svg>
  `,
});
